package com.bicon.botu.core.base.validate.parser;

import com.bicon.botu.core.base.validate.Result;
import com.bicon.botu.core.base.validate.annotation.Size;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.text.MessageFormat;

/**
 * 验证数值是否在 (min,max]区间内
 *
 * @version 1.0.0
 * @author: Gyb
 * @date 2018/3/5
 * @description
 **/
public class SizeParser implements Parser {

    private static final String DEFAULT_MESSAGE = "属性{0}的范围错误，应在[{1},{2}]区间内";

    @Override
    public Result parse(Field field, Object value) {
        if (field.isAnnotationPresent(Size.class) && checkFieldType(field)) {
            Result result = new Result();
            result.setFieldName(field.getName());
            Size size = field.getAnnotation(Size.class);
            Long l = value != null ? Long.valueOf(String.valueOf(value)) : 0;
            boolean isPassed = l >= (size).min() && l <= (size).max();
            result.setPassed(isPassed);
            String message = size.message();
            if (StringUtils.isEmpty(message)) {
                result.setMessage(MessageFormat.format(DEFAULT_MESSAGE, field.getName(), size.min(), size.max()));
            } else {
                result.setMessage(size.message());
            }
            return result;
        }
        return null;
    }

    @Override
    public boolean checkFieldType(Field field) {
        return field.getType() == Long.class || field.getType() == Short.class || field.getType() == Integer.class;
    }
}
